<?php


namespace app\api\service;

use think\Cache;

class Accesstoken{

    protected $appid;
    protected $secret;
    protected $accessUrl;
    protected $templateUrl;
    const TOKEN_CACHED_KEY = 'access_token';
    const TOKEN_EXPIRE_IN = 7150;

    public function __construct(){
        Cache::rm(self::TOKEN_CACHED_KEY);
        $this->appid = Config('wxinfo.appId');
        $this->secret = Config('wxinfo.secretId');
        $this->accessUrl = Config('wxinfo.accessUrl');
    }

    /**
     * 获取access_token
     *
     * @return array  返回access_token
     */
    public function getToken(){
        $access_token = Cache::get(self::TOKEN_CACHED_KEY);
        if($access_token){
            return ['access_token'=>$access_token];
        }
        return $this->getAccessToken();
    }
    protected function getAccessToken(){
        $url = sprintf($this->accessUrl,$this->appid,$this->secret);
        $result = https_request($url);
        $acResult = json_decode($result,true);

        if(array_key_exists('errcode',$acResult) && $acResult['errcode'] !=0){
            return ['code'=>$acResult['errcode'],'msg'=>$acResult['errmsg']];
        }
        Cache::set(self::TOKEN_CACHED_KEY,$acResult['access_token'],self::TOKEN_EXPIRE_IN);
        return ['access_token'=>$acResult['access_token']];
    }

    /**
     * 保存openid信息
     *
     */
    static public function setTokenByOpenid($data){
        $token = md5(random(32));
        Cache::set($token,$data,self::TOKEN_EXPIRE_IN);
        return $token;
    }

    static public function getMemberByToken($token){
        return Cache::get($token);
    }

    static public function checkToken($token){
        $item = Cache::get($token);
        if(!isset($item)){
            return ['code'=>-1,'msg'=>'token不存在'];
        }
        return ['code'=>1,'msg'=>'token存在'];
    }
}


